package com.ruoyi.project.system.lotto.controller;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.system.lotto.domain.ResObject;
import com.ruoyi.project.system.lotto.domain.Rewards;
import com.ruoyi.project.system.lotto.service.RewardsService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 奖品控制器
 */
@Api("奖品管理")
@RequestMapping("/rewards")
@CrossOrigin(allowCredentials="true",maxAge = 3600)
@RestController
public class RewardsController {
    @Autowired
    private RewardsService rewardsService;

    /**
     * 奖品列表
     * @return
     */
    @CrossOrigin
    @PostMapping("list")
    @ResponseBody
    public ResObject list() {
        List<Rewards> rewards = rewardsService.getList();

        if (rewards.isEmpty()) {
            return ResObject.success("查询为空");
        }

        return ResObject.success("查询成功", rewards);
    }

    /**
     * 新增奖品
     * @return
     */
    @CrossOrigin
    @Log(title = "奖品管理", businessType = BusinessType.INSERT)
    @PostMapping("save")
    @ResponseBody
    public ResObject save(@RequestBody Rewards rewards) {
        if (StrUtil.isBlank(rewards.getName()) || rewards.getStock() == null || rewards.getStock() < 1) {
            return ResObject.error("奖品名称或库存不可为空");
        }

        try {
            rewardsService.insert(rewards);
            return ResObject.success("新增成功");
        } catch (Exception e) {
            return ResObject.success("新增失败");
        }
    }

    /**
     * 更新
     * @return
     */
    @CrossOrigin
    @Log(title = "奖品管理", businessType = BusinessType.UPDATE)
    @PostMapping("update")
    @ResponseBody
    public ResObject update(@RequestBody Rewards rewards) {
        if (StrUtil.isBlank(rewards.getName()) || rewards.getStock() == null) {
            return ResObject.error("奖品名称或库存不可为空");
        }

        try {
            rewardsService.updateByPrimaryKeySelective(rewards);
            return ResObject.success("修改成功");
        } catch (Exception e) {
            return ResObject.success("修改失败");
        }
    }

    /**
     * 获取详情
     * @return
     */
    @CrossOrigin
    @PostMapping("detail")
    @ResponseBody
    public ResObject detail(@RequestBody Rewards rewards) {
        if (rewards.getId() == null) {
            return ResObject.error("id不可为空");
        }

        Rewards reward = rewardsService.selectByPrimaryKey(rewards.getId());
        return ResObject.success("查询成功", reward);
    }
}
